<?php
/**
 * 用户操作类
 * Created		: 2012-05-28
 * Modified		: 2012-06-19
 * @version		: 1.0.0
 * @author		: Joseph Chen (chenliq@gmail.com)
 */
class User 
{
	/**
	 * 是否已登录
	 * @var boolean
	 */
	private static $isLogined = false;
	/**
	 * 用户表
	 * @var string
	 */
	public static $tbl = 'user';
	/**
	 * 用户登录表
	 * @var string
	 */
	public static $tbl_login = 'user_login';
	/**
	 * 错误提示信息
	 * @var string
	 */
	public static $msg = '';
	/**
	 * 当前登录用户的数据
	 * @var array
	 */
	public static $data = array();
	
	/**
	 * 初始化用户数据
	 */
	public static function init()
	{
		if (empty($_SESSION['uid']) || empty($_SESSION['username'])) {
			self::$isLogined = false;
			unset($_SESSION['uid'], $_SESSION['username']);
			self::$data = array();
		} else {
			self::$isLogined = true;
			self::$data = self::read($_SESSION['uid']);
		}
	}
	
	/**
	 * 判断当前用户是否已登录
	 * @param string|int $username
	 * @return boolean
	 */
	public static function isLogined($username=null) 
	{
		// 默认取当前用户
		if (is_null($username)) {
			return self::$isLogined;
		}
		// 纯数字ID说明是用户ID(系统限制用户名不能为纯数字ID)
		else if (!$GLOBALS['_username_only_digit'] && ctype_digit((string)$username)) {
			return Cache::get('uol:'.$username);
		} else {
			return Cache::get('uol:'.self::getUidByUsername($username));
		}
	}
	
	/**
	 * 根据用户名获取用户ID
	 * @param string $username
	 * @return int
	 */
	public static function getUidByUsername($username) 
	{
		$uid = Cache::get('uid'.$username);
		if (!$uid) {
			$uid = Db::read(self::$tbl, $value, 'username', 'uid');
			if ($uid) {
				// 数据缓存10天
				Cache::set('uid'.$username, $uid, 864000);
			}
		}
		return (boolean)$uid;
	}
	
	/**
	 * 读取用户信息
	 * @param string $val
	 * @param string $field
	 */
	public static function read($val, $fetchFields='*', $field='uid', $useCache=true) 
	{
		if ($GLOBALS['_cache_enable'] && $useCache) {
			if ($field != 'uid') {
				$val = self::getUidByUsername($val);
			}
			$key = 'u:'.$val;
			if ($fetchFields=='' || $fetchFields=='*') {
				$fetchFields = null;
			} else if (is_string($fetchFields)) {
				$fetchFields = explode(',', $fetchFields);
			}
			$record = Cache::getHash($key, $fetchFields);
			if (!$record) {
				$record = Db::read(self::$tbl, $val, $field);
				Cache::setHash($key, $record, $GLOBALS['_cache_user_expire']);
			}
		} else {
			$record = Db::read(self::$tbl, $val, $field, $fetchFields);
		}
		return $record;
	}
	
	/**
	 * 读取用户登录信息
	 * @param int $uid
	 */
	public static function readLoginInfo($uid)
	{
		return Db::read(self::$tbl_login, $uid);
	}
	
	/**
	 * 用户账号密码验证
	 * @param string $user
	 * @param string $pass
	 * @param boolean $cacheData 验证成功是否缓存数据
	 */
	public static function verify($username, $pass, $cacheData=true)
	{
		$user = Db::read(self::$tbl_login, $username, 'username');
		// 用户名不存在
		if (!$user) {
			self::$msg = Core::getLang('username_not_exist');
			return false;
		} else if (self::hashPassword($pass, $user['salt']) == $user['password']) {
			self::$msg = Core::getLang('login_success');
			$_SESSION['uid']		= $user['uid'];
			$_SESSION['username']	= $username;
			if ($cacheData) {
				Cache::setHash('u'.$user['uid'], $user, $GLOBALS['_cache_user_expire']);
			}
			return true;
		} else { //密码错误
			self::$msg = Core::getLang('password_incorrect');
			return false;
		}
	}
	
	/**
	 * 加密密码
	 * @param string $pass
	 * @param string $salt
	 * @return string
	 */
	public static function hashPassword($password, $salt)
	{
		return md5(md5(md5($password).md5($salt)));
	}
	
	/**
	 * 加密客户端SID值
	 * @param int $uid
	 * @return string
	 */
	public static function hashSid ($uid)
	{
		$loginInfo = self::readLoginInfo($uid);
		return md5(md5($uid).md5($loginInfo['sid_time']).$loginInfo['salt']);;
	}
	
	/**
	 * 添加用户的部分字段值
	 * @param int $uid
	 * @param int $val 增加的值
	 * @param int $cid 操作分类ID
	 * @param string $field 增加值的字段
	 * @param int $gameId 涉及的游戏ID
	 * @param int $serverId 涉及的服务器ID
	 * @param string $orderNo 订单号
	 * @param string $content 内容
	 */
	public static function addVal($uid, $val, $cid, $field='gold', $gameId=0, $serverId=0, $orderNo='', $content='') 
	{
		// 先判断操作字段是否在可允许列表
		$allowField = array('gold', 'gold_bond', 'coin', 'credit');
		if (!in_array($filed, $allowField)) {
			self::$msg = Core::getLang('user_add_val_field_unallowed');
			return false;
		}
		$uid = (int)$uid;
		$user = self::read($uid, 'username,'.$field);
		// 判断字段值是否足够
		if ($user[$field] < $val) {
			self::$msg = Core::getLang($field.'_value_not_enough');
			return false;
		}
		$game = Game::read($gameId);
		$server = Game::readServer($serverId);
		Db::beginTransaction();
		
		switch ($field)
		{
			// 金币记录
			case 'gold':
				$log = array(
					'cid'			=> $cid,
					'order_no'		=> $orderNo,
					'is_bond'		=> 0,
					'uid'			=> $uid,
					'username'		=> $user['username'],
					'num'			=> $val,
					'game_id'		=> $gameId,
					'server_id'		=> $serverId,
					'game_name'		=> $game['name'],
					'server_name'	=> $server['name'],
					'create_time'	=> time(),
					'content'		=> $content,
				);
				$ret = Db::insert('gold_log', $log);
			break;
			// 金券记录
			case 'gold_bond':
				$log = array(
					'cid'			=> $cid,
					'order_no'		=> $orderNo,
					'is_bond'		=> 1,
					'uid'			=> $uid,
					'username'		=> $user['username'],
					'num'			=> $val,
					'game_id'		=> $gameId,
					'server_id'		=> $serverId,
					'game_name'		=> $game['name'],
					'server_name'	=> $server['name'],
					'create_time'	=> time(),
					'content'		=> $content,
				);
				$ret = Db::insert('gold_log', $log);
			break;
			
			default:
				return false;
			break;
		};
		// 进行用户数据字段更新
		if ($ret) {
			$record = array(
				$field	=> $val
			);
			$ret = Db::update(self::$tbl, $record, 'uid='.$uid);
		}
		if ($ret) {
			Db::commit();
			return true;
		} else {
			Db::rollBack();
			return false;
		}
	}
	
}